<?php
namespace app\appletsapi\controller;

// 公共类
use app\common\model\User;
use Firebase\JWT\JWT as JWTUtil;
use think\Controller;
use think\facade\Config;
use think\facade\Request;

class Base extends Controller
{
	public $_userid;
	public $limit = 10;
	public $_shopid = 0;
	public $_seatid = 0;
	public $_userInfo = [];

	public function __construct()
	{
//		echo $this->createjwt(['time'=>time(),'user_id'=>323,'nick_name'=>111,'type'=>'offline','shop_id'=>1,'seat_num'=>1]);die;
		parent::__construct();
		header('Content-Type: text/html;charset=utf-8');
		header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
		header('Access-Control-Allow-Methods:GET,POST,OPTIONS,PUT,DELETE,PATCH'); // 允许请求的类型
		header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
		header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
		$this->checkToken();
		$this->limit = input('limit');
	}

	protected function checkToken()
	{
		$controller = Request()->controller(); //获取控制器名
		$action = Request()->action(); //获取方法名
		$path = $controller.'/'.$action;
		//获取不需要token的页面数组
		$excepts = config::pull('NoTokenApi');
		//循环判断本页面是否需要在这个数组里面
		$isExcept = in_array(strtolower($path),$excepts);
		if (!$isExcept){
			$this->verifyJwt();
		}
//		$this->checkShopAndSeat($path);
	}

    /**
     * 验证token
     * &#64;return \think\response\Json
     */
    public function verifyJwt()
    {
        $token = Request::instance()->header('token');
        try{
            if(!$token){
                throw new \think\exception\HttpException(-2, 'token error');
            }
            $key = md5(config::get('token.key')); //jwt的签发密钥，验证token的时候需要用到
            $jwtAuth = json_encode(JWTUtil::decode($token,$key,['HS256']));
            $authInfo = json_decode($jwtAuth,true);

            if(empty($authInfo['exp']) || $authInfo['exp'] < time()){
                throw new \think\exception\HttpException(-2, '登录过期');
//                $this->result([],-2,'登录过期');
            }
            if (empty($authInfo['user_id'])){
                throw new \think\exception\HttpException(-2, 'user error');
//                $this->result([],-2,'user error');
            }
            $userModel = new User();
            $user = $userModel->field('*')->where(['user_id'=>$authInfo['user_id']])->find();
            if(!$user){
                throw new \think\exception\HttpException(-2, 'user error');
//                $this->result([],-2,'user error');
            }
        }catch (\Exception $e){
//            throw new \think\exception\HttpException(-2, $e->getMessage());
            $this->result([],-2,$e->getMessage());
        }

        $this->_userid = $authInfo['user_id'];
        $this->_userInfo = $user->toArray();

    }

    // 返回身份数据
    function GetUserInfo()
    {
//        $UserModel = new \app\common\model\User();
//    $user = $UserModel->field('*')->where(['user_id'=>$this->_userid])->find();
//        if(!empty($user)){
//            $user = $user->toArray();
//        }
        return $this->_userInfo;
    }

    /**
     * 验证店铺id和座位id
     * &#64;return \think\response\Json
     */
    public function checkShopAndSeat($path)
    {
        $excepts = config::pull('CheckShopAndSeat');
        $isShop = in_array(strtolower($path),$excepts['shop']);
        if ($isShop){
            $shop_id = input('shop_id');
            !isset($shop_id)?$this->result([],-1,'商铺有误'):$this->_shopid = $shop_id;
        }
        $isSeat = in_array(strtolower($path),$excepts['seat']);
        if ($isSeat){
            $seat_id = input('seat_id');
            empty($seat_id)?$this->result([],-1,'座位有误'):$this->_seatid = $seat_id;
        }
    }
}
